// Parse the time to string
export const parseTime = (
  time?: object | string | number,
  cFormat?: string
): string | null => {
  if (time === undefined) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date: Date
  if (typeof time === 'object') {
    date = time as Date
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: { [key: string]: number } = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return timeStr
}

export const formatSecond = (second: number | string) => {
  let h = 0, m = 0, s = Number(second)
  if(s >=60) {
    m = Math.floor(s / 60)
    s = s % 60
  }
  if(m >= 60) {
    h = Math.floor(m / 60)
    m = m % 60
  }
  const timeStr = (time: number) => {
    return time >= 10 ? time : '0' + time
  }
  return `${timeStr(h)}:${timeStr(m)}:${timeStr(s)}`
}

// Format and filter json data using filterKeys array
export const formatJson = (filterKeys: any, jsonData: any) =>
  jsonData.map((data: any) => filterKeys.map((key: string) => {
    if (key === 'timestamp') {
      return parseTime(data[key])
    } else {
      return data[key]
    }
  }))

// Check if an element has a class
export const hasClass = (ele: HTMLElement, className: string) => {
  return !!ele.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
}

// Add class to element
export const addClass = (ele: HTMLElement, className: string) => {
  if (!hasClass(ele, className)) ele.className += ' ' + className
}

// Remove class from element
export const removeClass = (ele: HTMLElement, className: string) => {
  if (hasClass(ele, className)) {
    const reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

// Toggle class for the selected element
export const toggleClass = (ele: HTMLElement, className: string) => {
  if (!ele || !className) {
    return
  }
  let classString = ele.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  ele.className = classString
}

/**
 * 导出文件
 * 参数 response导出的文件内容 name:导出的文件名称
 */
 export const download = (response: any, name: any) => {
  // debugger
  const content = response
  const blob = new Blob([content])
  const fileName = name
  if ('msSaveOrOpenBlob' in navigator) {
    //ie使用的下载方式
    window.navigator.msSaveOrOpenBlob(blob, fileName);
    return
  }
  const elink = document.createElement('a')
  elink.download = fileName
  elink.style.display = 'none'
  elink.href = URL.createObjectURL(blob)
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href) // 释放URL 对象
  document.body.removeChild(elink)
}

export const downloadFile = (url: string, params?: any) => {
  let paStr = '?'
  for (const key in params) {
    const item = params[key];
    paStr += `${key}=${item||""}&`
  }
  url = url + paStr
  url = encodeURI(url)
  window.open(url, '_bank')
}

/**
 * 比较时间大小(a>b=>true)
 * @param a 开始时间
 * @param b 结束时间
 * @returns
 */
export const compareDate = (a: string, b: string) => {
  const aDate = new Date(a)
  const bDate = new Date(b)
  if (aDate.getTime() >= bDate.getTime()) {
    return true
  } else {
    return false
  }
}

/**
 * 创建时间戳
 *
 */
export const createTime = () => {
  return new Date().getTime()
}

/**
 * base64转文件对象
 *
 */
export const dataURLtoFile = (dataurl: any, filename: any) => {
  let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

/**
 * 获取裁剪图片
 *
 */
export const curPictureFun = (dataurl: string, size: string = '_400x800') => {
  let arr = dataurl.split(/(.png|.jpg|.gif|.jpeg|.bmp|.tif)$/)
  let newUrl = arr[0] + size + arr[1]
  return newUrl;
}

/**
 * 深拷贝
 */
export const deepClone = (target: any) => {
  let result: any;
  if (typeof target === 'object') {
    if (Array.isArray(target)) {
      result = [];
      for (let i in target) {
        result.push(deepClone(target[i]))
      }
    } else if (target === null) {
      result = null;
    } else if (target.constructor === RegExp) {
      result = target;
    } else {
      result = {};
      for (let i in target) {
        result[i] = deepClone(target[i]);
      }
    }
  } else {
    result = target;
  }
  return result;
}
